#-*-coding:utf-8-*-
'''
Created on 2011-1-16

@author: zhaoyh
'''

import web

from admin.config import view
from db.org import Department
import admin.models.department as m_dept
from db.settings import get_setting
from core.meta import PageList,DBSession,makewhere
from utils.utility import coderule,AppStatus
status=AppStatus()
compo_name='部门'
compo_coderule=get_setting('department_code') 


class resource():
    '''
             请求页面时使用get，提交数据时使用post
    '''
    pass


class list():
    '''
         请求页面时使用get，提交数据时使用post
    TODO：可以用一个pagemaker对象，组装页面所需要的东西，这样就可以输出任何东西了，html，xml，json等
    '''
    def GET(self,name):
        page=web.input(numPerPage=20,pageNum=1,keywords='',orderField='dept_code',col='')
        #titles={'group_code':'用户组代码','group_name':'用户组名称','note':'备注'}    
        titles=web.Storage({'dept_code':'部门代码',
                            'dept_name':'部门名称',
                            'levels':' 级 次 ',
                            'is_active':' 启 用 ',
                            'dept_notes':' 备 注 '}   )
        where=makewhere(page.keywords,page.col,titles)        
        list=PageList(Department,page,where)
        return view.department_list(list=list.list(),page=list.Pageinfo(),title=titles)
    def POST(self,name):
        return self.GET(name)
    
class add():
    """
    TODO:服务器端校验还没做
    """
    
    def GET(self):        
        return view.department_add(rule=compo_coderule)
    def POST(self):
        u=web.input(is_active='N')
        r=coderule(compo_coderule)
        dept=m_dept.DepartmentModel()
        print r
        
        #if dept.get_code_setting("setting")
        
        try:#判断代码是否符合规则，不符合抛出ValueError错误
            levels=r.index(len(u['dept_code']))+1 #代码级次有错误抛出
            #T=DBSession.query(Department).filter(Department.dept_code==u['dept_code']).first()
            if DBSession.query(Department).filter(Department.dept_code==u['dept_code']).first(): 
                status.statusCode='error'
                status.message="%s代码重复" %compo_name
            p_code=u.dept_code[0:r[levels-2]]#父代码
            D=Department(u.dept_code,u.dept_name)
            D.levels=levels
            D.is_active=u.is_active
            D.dept_notes=u.dept_notes
            D.is_detail='Y'
            if levels<>1:
                P=DBSession.query(Department).filter(Department.dept_code==p_code).first()                
                print 'p_object-',P      
                if P==None:
                    status.statusCode='error'
                    status.message="%s代码的上级代码不存在请先增加上级" %compo_name
                elif P.is_active=='N':
                    status.statusCode='error'
                    status.message="%s代码的上级%s已经停用，请先启用" %(compo_name,compo_name)
                else:
                    P.is_detail='N'
                    D.parent_id=P.dept_id
                    D.dept_fullname=P.dept_fullname+'_'+D.dept_name
            else:
                D.dept_fullname=u.dept_name
            DBSession.add(D)
            DBSession.commit()
            DBSession.flush()
            status.statusCode='ok'
            status.message="添加成功" 
            status.navTabId="group_list"
        except ValueError:
            DBSession.rollback()
            status.statusCode='error'
            status.message="不符合编码规则"
        except Exception,e:
            DBSession.rollback()
            print Exception,e
            status.statusCode='error'
            status.message="保存错误%s" %e 
        return  status.status()
            
class edit():
    def GET(self,dept_id):
        edit_dept=DBSession.query(Department).filter(Department.dept_id==dept_id).first()
        if edit_dept==None:
            return  '{"statusCode":"300", "message":"数据已删除请刷新后重试"}'        
        parent=DBSession.query(Department).filter(Department.dept_id==edit_dept.parent_id).first()
        if parent==None:
            parent=web.Storage
            parent.dept_code=''
            parent.dept_name=''
        return view.department_edit(d=edit_dept,p=parent,rule=compo_coderule)
    def POST(self,dept_id):
        u=web.input(is_active='N')
        dept_name=u['dept_name']
        try:
            edit_dept=DBSession.query(Department).filter(Department.dept_id==dept_id).first()
            print u
            if edit_dept==None:
                status.statusCode='error'
                status.message="数据已删除请刷新后重试" 
            else:           
                edit_dept.dept_name=dept_name
                edit_dept.dept_fullname=edit_dept.dept_fullname[0:edit_dept.dept_fullname.rfind('_')+1]+dept_name                 
                edit_dept.dept_notes=u.dept_notes
                edit_dept.is_active=u.is_active                 
                DBSession.commit()
                DBSession.flush()
                if  edit_dept.is_detail=='N':                
                    r=coderule(compo_coderule)
                    for i in range(edit_dept.levels+1,len(r)+1):
                        try:                   
                            sql='''update ad_department b
                                    set dept_fullname=a.dept_fullname||'_'||b.dept_name
                                    from ad_department as a
                                    Where b.levels = %d   and a.dept_id = b.parent_id 
                                     And b.dept_Code Like '%s%%'  ; ''' %(i,edit_dept.dept_code)
                            print sql
                            DBSession.execute(sql)
                        except Exception:
                            break
                DBSession.commit()
                DBSession.flush() 
                status.statusCode='ok'
                status.message="添加成功" 
                status.navTabId="group_list"
        except Exception,e:
            DBSession.rollback()
            print Exception,e
            status.statusCode='error'
            status.message="保存错误%s" %e 
        return  status.status()
class delete():
    def POST(self,dept_id):
        try:
            edit_dept=DBSession.query(Department).filter(Department.dept_id==dept_id).first() 
            if edit_dept==None:
                status.statusCode='error'
                status.message="数据已删除请刷新后重试"
            else: 
                if edit_dept.levels>1:
                    parent_count=DBSession.query(Department).filter(Department.parent_id==edit_dept.parent_id).count()
                    if parent_count==1:
                        parent=DBSession.query(Department).filter(Department.dept_id==edit_dept.parent_id).first()
                    if parent!=None:
                            parent.is_detail='Y'
                count2=DBSession.query(Department).filter(Department.parent_id==edit_dept.dept_id).count()
                if count2>0:
                    status.statusCode='error'
                    status.message="请先删除上级" 
                else:  
                    DBSession.delete(edit_dept)
                    DBSession.commit()
                    DBSession.flush()
                    status.statusCode='ok'
                    status.message="删除成功"
                    status.navTabId='department_list' 
        except Exception,e:
            DBSession.rollback()
            print Exception,e
            status.statusCode='error'
            status.message="删除错误,%s" % e 
        return  status.status()